Page({
	data: {
		name: '',
		position: {
			latitude: 39.911057,
			longitude: 116.484143,
		},
		images: [],
		note: '',

	},
	onLoad(options) {
		if (options.position) {
			let position = JSON.parse(options.position)
			this.setData({
				position: {
					latitude: position.latitude,
					longitude: position.longitude,
				}
			})
		}
	},
	addimage() {
		let that = this;
		wx.chooseImage({
			count: 1,
			success: chooseResult => {
				wx.showLoading({
					title: '上传中',
				})
				wx.cloud.init()
				console.log(chooseResult.tempFilePaths[0], '<<<<')
				// 将图片上传至云存储空间
				wx.cloud.uploadFile({
					cloudPath: (new Date()).valueOf() + '.png',
					filePath: chooseResult.tempFilePaths[0], // 文件路径
				}).then(res => {
					wx.hideLoading()
					wx.cloud.getTempFileURL({
						fileList: [res.fileID]
					}).then(res => {
						let newimages = that.data.images
						newimages.push(res.fileList[0].tempFileURL)
						that.setData({
							images: newimages
						})
						wx.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 2000
						})
					}).catch(error => {
						console.log(error);
						wx.showToast({
							title: '上传失败',
							icon: 'error',
							duration: 2000
						})
					})

				}).catch(error => {
					wx.hideLoading()
					wx.showToast({
						title: '上传失败',
						icon: 'error',
						duration: 2000
					})
				})
			},
			fail(err) {
				console.log(err)
				wx.showToast({
					title: '取消上传',
					icon: 'error',
					duration: 2000
				})
			}
		})
	},
	removeImg: function (event) {
		let index = event.currentTarget.dataset.index
		let newimages = []
		for (var a = 0; a < this.data.images.length; a++) {
			if (a != index) {
				newimages.push(this.data.images[a])
			}
		}
		this.setData({
			images: newimages
		})
	},
	submit() {
		let that = this;
		wx.cloud.init()
		const db = wx.cloud.database()
		db.collection('markers').add({
				// data 字段表示需新增的 JSON 数据
				data: {
					id: Date.parse(new Date()),
					name: that.data.name,
					iconPath: that.data.images[0],
					images: that.data.images,
					note: that.data.note,
					latitude: that.data.position.latitude,
					longitude: that.data.position.longitude,
					ctime: new Date().toLocaleString(),
				}
			})
			.then(res => {
				console.log(res)
				wx.showToast({
					title: '提交成功',
					icon: 'success',
					duration: 2000
				})
			}).catch(err => {
				console.log(err)
				wx.showToast({
					title: '提交失败',
					icon: 'error',
					duration: 2000
				})
			})
		wx.navigateBack({
			delta: 1
		})
	},
})